<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8" />
    <title>15_鼠标拖拽-拖拽过快问题</title>
    <style>
        * {
            margin: 0;
            padding: 0;
        }

        div {
            position: absolute;
            width: 100px;
            height: 100px;
            background-color: aqua;
        }
    </style>
</head>

<body>
    <div>尚硅谷</div>

    <script>
        var div = document.querySelector('div');

        div.onmousedown = function (event) {
            var eleX = div.offsetLeft;
            var eleY = div.offsetTop;

            var startX = event.clientX;
            var startY = event.clientY;

            document.onmousemove = function (event) {
                var endX = event.clientX;
                var endY = event.clientY;

                var disX = endX - startX;
                var disY = endY - startY;

                var lastX = eleX + disX;
                var lastY = eleY + disY;

                // 左右
                if(lastX >= document.documentElement.clientWidth - div.offsetWidth){
                    lastX = document.documentElement.clientWidth - div.offsetWidth;
                }else if(lastX <= 0){
                    lastX = 0;
                }
                // 上下
                if(lastY >= document.documentElement.clientHeight - div.clientHeight){
                    lastY = document.documentElement.clientHeight - div.clientHeight;
                }else if(lastY <= 0){
                    lastY = 0;
                }

                // 吸附效果
                if(lastX >= document.documentElement.clientWidth - div.offsetWidth - 50){
                    lastX = document.documentElement.clientWidth - div.offsetWidth;
                }else if(lastX <= 50){
                    lastX = 0;
                }


                if(lastY >= document.documentElement.clientHeight - div.clientHeight - 50){
                    lastY = document.documentElement.clientHeight - div.clientHeight;
                }else if(lastY <= 50){
                    lastY = 0;
                }




                div.style.left = lastX + 'px';
                div.style.top = lastY + 'px';
            }

            // console.log(div.onmousemove);
            document.onmouseup = function () {
                document.onmousemove = document.onmouseup = null;
            }

            // 取消浏览器默认行为
            return false;

        }

    </script>
</body>

</html>